package top.infopub.mgr.bpa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.mgr.bpa.dao.ContractNegDao;
import top.infopub.mgr.bpa.domain.BpaProjectDomain;
import top.infopub.mgr.bpa.domain.ContractLedgerDomain;
import top.infopub.mgr.bpa.domain.ContractNegDomain;
import top.infopub.mgr.bpa.dto.ContractNegDto;
import top.infopub.mgr.bpa.jsonVo.ContractNegJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.ContractNegService;
import top.infopub.mgr.bpa.vo.ContractManageVo;
import top.infopub.mgr.bpa.vo.ContractPublicVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.model.bpa.BpaContractNeg;
import top.infopub.model.bpa.ContractNegProcess;
import top.infopub.model.cap.LookInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: Tszzzzzz
 * @Date: 2021/6/4
 */
@Service
public class ContractNegServiceImpl implements ContractNegService {

    @Autowired
    private ContractNegDao contractNegDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;

    @Override
    public Page<ContractNegDomain> selectByDomainWhere(Page<ContractNegDomain> page, ContractPublicVo contractPublicVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(contractPublicVo.getDates())) {
            String[] splitTime = contractPublicVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                contractPublicVo.setEndDate(format.parse(splitTime[1]));
                contractPublicVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ContractNegDomain>)contractNegDao.selectByDomainWhere(contractPublicVo);
    }

    @Override
    public Page<ContractLedgerDomain> selectByLedger(Page<ContractLedgerDomain> page, ContractManageVo contractManageVo) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(contractManageVo.getDates()))
        {
            String[] splitTime = contractManageVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            contractManageVo.setStartDate(format.parse(splitTime[0]));
            contractManageVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ContractLedgerDomain>)contractNegDao.selectByLedger(contractManageVo);
    }

    @Override
    public ContractNegJsonVo queryDetailById(String id) {
        ContractNegJsonVo contractNegJsonVo = new ContractNegJsonVo();
        ContractNegDto contractNegDto = contractNegDao.queryDetailById(id);
        contractNegJsonVo.setContractNegDto(contractNegDto);
        //进展信息
       List<ContractNegProcess> processes = contractNegDao.selectProcess(id);
       contractNegJsonVo.setProcesses(processes);

       //附件信息 ---待定
        List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(contractNegDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE62.getCode(), null);
        contractNegJsonVo.setFileAtt(fileAttaListToArray(attachmentList));
        return contractNegJsonVo;
    }

    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
        if (list == null || list.size() <= 0) return null;
        String[] attaArr = new String[list.size()];
        int index = 0;
        for (ProjectAttachment pa : list) {
            StringBuffer tmp = new StringBuffer();
            tmp.append(pa.getSubTypes());
            tmp.append("|");
            tmp.append(pa.getFileName());
            tmp.append(pa.getFileSuffix());
            tmp.append("|");
            tmp.append(IdFactory.getUUIDSerialNumber());
            tmp.append("|");
            tmp.append(pa.getFilePath());
            attaArr[index] = tmp.toString();
            index++;
        }
        return attaArr;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo saveAll(AuthorizationVO userDtl, BpaContractNeg contractNeg, List<ProjectAttachment> attachmentList, String bodyStr, Integer submitType) {
        //处理主表信息
        if(StringUtils.isNotBlank(contractNeg.getId())){//编辑
            contractNegDao.updateById(contractNeg);
        }else{
            contractNegDao.insertById(contractNeg);
        }
        //处理子表信息
        if (StringUtils.isNotBlank(contractNeg.getClauseDispute())){//为子表添加数据
            ContractNegProcess contractNegProcess = new ContractNegProcess();
            contractNegProcess.setId(IdFactory.getUUIDUpper());
            contractNegProcess.setAddBy(userDtl.getId());
            contractNegProcess.setAddTime(new Date());
            contractNegProcess.setNegId(contractNeg.getId());
            contractNegProcess.setClauseDispute(contractNeg.getClauseDispute());
            contractNegProcess.setNegConclusion(contractNeg.getNegConclusion());
            contractNegProcess.setAgreedTerms(contractNeg.getAgreedTerms());
            contractNegProcess.setNegEntry(contractNeg.getNegEntry());
            contractNegProcess.setOurHead(contractNeg.getOurHead());
            contractNegProcess.setOtherPartyHead(contractNeg.getOtherPartyHead());
            contractNegDao.insertProcess(contractNegProcess);
        }

        if (attachmentList!=null && attachmentList.size()>0){
            //批量插入附件信息
            projectAttachmentDao.deleteByWhere(contractNeg.getProCode(), ProjectFileTypeEnum.FILE_TYPE62.getCode(), null);
            for (ProjectAttachment attachment : attachmentList) {
                attachment.setProCode(contractNeg.getProCode());
            }
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType==2){
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE1, bodyStr, contractNeg.getId(), contractNeg.getProCode(), userDtl);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public List<BpaProjectDomain> queryByProCode() {

        return contractNegDao.queryByProCode();
    }

    @Override
    public BpaContractNeg selectBySguid(String id) {
        return contractNegDao.selectBySguid(id);
    }
}
